/**
* 合同
*/
<template>
    <el-form v-loading="loading" :model="formData" :rules="isEditPage ? formRules : {}" ref="formRef"
        label-width="120px" :scroll-to-error="true">
        <vp-card>
            <el-row style="flex: 1;">
                <vp-col :span="3">
                    <el-form-item prop="lx">
                        <template #label><vp-label zh="类型" en="" align="left" /></template>
                        <el-select class="w100" v-model="formData.lx" clearable v-if="type == 'add'">
                            <el-option :value="10" label="采购/"></el-option>
                            <el-option :value="20" label="送修/"></el-option>
                            <el-option :value="30" label="借入/"></el-option>
                            <el-option :value="40" label="借出/"></el-option>
                            <el-option :value="50" label="交换/"></el-option>
                            <el-option :value="70" label="出租/"></el-option>
                            <el-option :value="80" label="销售/"></el-option>
                            <el-option :value="90" label="索赔/"></el-option>
                            <el-option :value="999" label="其他/"></el-option>
                        </el-select>
                        <span v-else>{{ formData.lx==10?'采购/':formData.lx==20?'送修/':formData.lx==30?'借入/':formData.lx==40?'借出/':
                        formData.lx==50?'交换/':formData.lx==70?'出租/':formData.lx==80?'销售/':formData.lx==90?'索赔/':formData.lx==999?'其他/':"" }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="3">
                    <el-form-item prop="bh">
                        <template #label><vp-label zh="合同号" en="" align="left" /></template>
                        <el-input v-model="formData.bh" maxlength="100" v-if="isEditPage">
                        </el-input>
                        <span v-else>{{ formData.bh }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="3">
                    <el-form-item prop="htrq">
                        <template #label><vp-label zh="合同日期" en="" /></template>
                        <el-date-picker v-if="isEditPage" v-model="formData.htrq" value-format="YYYY-MM-DD" type="date"
                            class="w100" />
                        <vp-text v-else>{{ formData.htrq }}</vp-text>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row>
                <vp-col :span="3">
                    <el-form-item prop="xgfms">
                        <template #label><vp-label zh="供应商/相关⽅" en="" align="left" /></template>
                        <el-input v-model="formData.xgfms" v-trim maxlength="20" v-if="isEditPage" readonly>
                            <template #append>
                                <el-button @click="handleSupplierSelected()">
                                    <SvgIcon name="ele-Search" />
                                </el-button>
                            </template>
                        </el-input>
                        <span v-else>{{ formData.xgfms }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="3">
                    <el-form-item prop="jffs">
                        <template #label><vp-label zh="交付方式" en="" align="left" /></template>
                        <VpDictSelect :lxid="405" :selectedId="formData.jffs"
                            @dictSelected="obj => { formData.jffs = obj; }" style="width:100%" v-if="isEditPage">
                        </VpDictSelect>
                        <span v-else>{{ formData.jffs }}</span>
                    </el-form-item>
                </vp-col>
                <vp-col :span="3">
                    <el-form-item prop="jylx">
                        <template #label><vp-label zh="交易类型" en="" align="left" /></template>
                        <VpDictSelect :lxid="406" :selectedId="formData.jylx"
                            @dictSelected="obj => { formData.jylx = obj; }" style="width:100%" v-if="isEditPage">
                        </VpDictSelect>
                        <span v-else>{{ formData.jylx }}</span>
                    </el-form-item>
                </vp-col>
            </el-row>
            <el-row>
                <vp-col :span="1">
                    <el-form-item prop="bz">
                        <template #label><vp-label zh="备注" en="" /></template>
                        <el-input type="textarea" v-model="formData.bz" maxlength="1000" :autosize="{ minRows: 2 }"
                            v-if="isEditPage">
                        </el-input>
                        <vp-text v-else>{{ formData.bz }}</vp-text>
                    </el-form-item>
                </vp-col>
            </el-row>

            <el-row>
                <vp-col :span="1">
                    <el-form-item prop="zslxList">
                        <template #label>
                            <vp-label zh="证书" en="" align="left" />
                        </template>
                        <VpDictCheckbox :lxid="407" :selectedId="formData.zslxList"
                            @onConfirm="obj => { formData.zslxList = obj; }" v-if="isEditPage">
                        </VpDictCheckbox>
                        <span v-else>{{ formData.zslxList.join(',') }}</span>
                    </el-form-item>
                </vp-col>
            </el-row>

            <el-row>
                <vp-col :span="1">
                    <el-form-item>
                        <template #label><vp-label zh="明细" en="" align="left" /></template>
                        <vp-vxe-table :data="formData.detailList" row-key="id" minHeight="300">
                            <vxe-column type="seq" align="center" title="#" width="50" />
                            <vxe-column field="jh">
                                <template #header><vp-label zh="件号/产品名" en="" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`detailList[${scope.rowIndex}].jh`" label-width="auto">
                                        <span>{{ scope.row.jh }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="zwms">
                                <template #header><vp-label zh="名称（英/中⽂）" en="" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`detailList[${scope.rowIndex}].zwms`" label-width="auto">
                                        <span>中文:{{ scope.row.zwms }} 英文:{{ scope.row.ywms }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="xqmxid" width="200">
                                <template #header><vp-label zh="关联需求" en="" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`detailList[${scope.rowIndex}].xqmxid`" label-width="auto">
                                        <el-input :value="`${scope.row.xqmxBh} #${scope.row.xqmxXc}`" v-if="isEditPage"
                                            readonly>
                                            <template #append>
                                                <el-button @click="handleAddMaterialDemandSingle(scope.row)">
                                                    <SvgIcon name="ele-Search" />
                                                </el-button>
                                            </template>
                                        </el-input>
                                        <span v-else>{{ scope.row.xqmxBh }} #{{ scope.row.xqmxXc }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="sl" width="190">
                                <template #header><vp-label zh="数量" en="" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`detailList[${scope.rowIndex}].sl`" :rules="formRules.datailSl"
                                        label-width="auto">
                                        <el-input-number v-model="scope.row.sl" :min="1" :max="999999"
                                            v-if="isEditPage" :disabled="(formData.lx==20 || formData.lx==30 || formData.lx==40 || formData.lx==50  || formData.lx==70)">
                                            <template #suffix>
                                                <span>{{ scope.row.jldw }}</span>
                                            </template>
                                        </el-input-number>
                                        <span v-else>{{ scope.row.sl }}{{ scope.row.jldw }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="xlh" width="190" v-if="formData.lx==20 || formData.lx==30 || formData.lx==40 || formData.lx==50  || formData.lx==70">
                                <template #header><vp-label zh="序列号" en="" /></template>
                                <template #default="scope">
                                    <el-form-item :prop="`detailList[${scope.rowIndex}].xlh`"
                                        :rules="formRules.datailXlh" label-width="auto">
                                        <el-input v-model="scope.row.xlh" v-if="isEditPage" />
                                        <span v-else>{{ scope.row.xlh }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="jhrq">
                                <template #header>
                                    <div class="header-item">
                                        <vp-label zh="交货期" en="" />
                                        <el-button  v-if="type!='view'" circle @click="handleAddJhqBeatch()">
                                            <SvgIcon name="ele-Setting"></SvgIcon>
                                        </el-button>
                                    </div>
                                </template>
                                <template #default="scope">
                                    <el-form-item :prop="`detailList[${scope.rowIndex}].zgkc`" label-width="auto">
                                        <el-date-picker v-if="isEditPage" v-model="scope.row.jhrq"
                                            value-format="YYYY-MM-DD" type="date" class="w100" />
                                        <vp-text v-else>{{ scope.row.jhrq }}</vp-text>
                                    </el-form-item>
                                </template>
                            </vxe-column>
                            <vxe-column field="cqBh">
                                <template #header>
                                    <div class="header-item">
                                        <vp-label zh="产权" en="" />
                                        <el-button v-if="type!='view'" circle @click="handleAddPropertyRightsBeatch()">
                                            <SvgIcon name="ele-Setting"></SvgIcon>
                                        </el-button>
                                    </div>
                                </template>
                                <template #default="scope">
                                    <el-form-item :prop="`detailList[${scope.rowIndex}].cqBh`" label-width="auto">
                                        <el-input :value="`${scope.row.cqBh} ${scope.row.cqName}`" v-trim maxlength="20"
                                            v-if="isEditPage" readonly>
                                            <template #append>
                                                <el-button @click="handleAddPropertyRights(scope.row)">
                                                    <SvgIcon name="ele-Search" />
                                                </el-button>
                                            </template>
                                        </el-input>
                                        <span v-else>{{ formData.xgfms }}</span>
                                    </el-form-item>
                                </template>
                            </vxe-column>


                            <vxe-column align="center" width="100" v-if="isEditPage">
                                <template #header>
                                    <el-popover placement="top-start">
                                        <template #reference>
                                            <el-button circle>
                                                <SvgIcon name="ele-Plus"></SvgIcon>
                                            </el-button>
                                        </template>
                                        <div class="box-item-content">
                                            <vp-btn type="text" @click="handleAddMaterialDemandBeatch()">
                                                <vp-label zh="需求" en="" />
                                            </vp-btn>
                                            <el-divider style="margin: 5px 0;"></el-divider>
                                            <vp-btn type="text" @click="handleAddBasedataMaterial()">
                                                <vp-label zh="物料" en="" />
                                            </vp-btn>
                                        </div>
                                    </el-popover>
                                </template>
                                <template #default="scope">
                                    <el-button circle @click="handleDeleteDetailLimit(scope.rowIndex)">
                                        <SvgIcon name="ele-Minus"></SvgIcon>
                                    </el-button>
                                </template>
                            </vxe-column>
                        </vp-vxe-table>
                    </el-form-item>
                </vp-col>
            </el-row>

            <VpFileListRow :attachmentList="formData.attachmentList" :readOnly="!isEditPage" :show-attachment="false"
                @attachmentListEmit="formData.attachmentList = $event">
                <template #header><vp-label zh="附件列表" en="File List" /></template>
            </VpFileListRow>
        </vp-card>

        <!-- 产权 -->
        <VpBasedataPropertyRightsDialog ref="vpBasedataPropertyRightsDialogRef" />
        <!--物料清单-->
        <VpBasedataMaterialDialog ref="vpBasedataMaterialDialog"></VpBasedataMaterialDialog>

        <!--选择需求-->
        <ChooseMaterialDemandDialog ref="chooseMaterialDemandDialogRef" />

        <!--选择供应商-->
        <ChooseQualitySupplierListDialog ref="chooseQualitySupplierListDialogRef" />

    </el-form>
</template>
<script setup lang="ts" name="Ata">
import { defineAsyncComponent, onMounted, ref, watch, computed, h } from "vue";
import request from "/@/utils/request";

import { ElMessageBox, ElMessage, ElDatePicker } from 'element-plus'

import validateUtils from "/@/utils/validateUtils";
import VpFileListRow from '/@/components/vp/file/VpFileListRow.vue';
import VpDictSelect from '/@/components/vp/dict/VpDictSelect.vue';
import VpDictCheckbox from '/@/components/vp/dict/VpDictCheckbox.vue';

import VpBasedataPropertyRightsDialog from '/@/components/vp/basedataPropertyRights/VpBasedataPropertyRightsDialog.vue';
import VpBasedataMaterialDialog from '/@/components/vp/basedataMaterial/VpBasedataMaterialDialog.vue';
import ChooseMaterialDemandDialog from '../dialogs/ChooseMaterialDemandDialog.vue';
import ChooseQualitySupplierListDialog from '../dialogs/ChooseQualitySupplierListDialog.vue';


const emits = defineEmits(['formSubmited']);


const formData = ref({
    id: null,
    zt: null,
    bh: "",
    lx: null,
    htrq: "",
    xgflx: null as any,
    xgfid: null,
    xgfms: null,
    jffs: "",
    jylx: "",
    bz: "",
    fjglid: "",
    attachmentList: [] as any[],

    zslxList: [] as any[],
    detailList: [] as any[],
});
const formRules = {
    lx: [validateUtils.notNull],
    bh: [validateUtils.notNull],
    htrq: [validateUtils.notNull],
    xgfms: [validateUtils.notNull],

    datailSl: [validateUtils.notNull],
    datailXlh: [validateUtils.notNull],
}

const initFormData = () => {
    formData.value = {
        id: null,
        zt: null,
        bh: "",
        lx: null,
        htrq: "",
        xgflx: null as any,
        xgfid: null,
        xgfms: null,
        jffs: "",
        jylx: "",
        bz: "",
        fjglid: "",
        attachmentList: [] as any[],

        zslxList: [] as any[],
        detailList: [] as any[],

    }
}

watch(
  () => formData.value.lx, 
  (newVal, oldVal) => {
    console.log("lx", newVal, oldVal);
    if(oldVal==20 ||  newVal==30 || oldVal==40 || newVal==50 || newVal==70){

        formData.value.detailList.forEach((row: any) => {
            row.sl = 1;
        });
    }
  }
)


const type = ref('add');
const loading = ref(false);
const formRef = ref();

const props = defineProps<{
    id: string,
    type: string,
}>()

onMounted(() => {
    handleOpen(props.type, props.id);
})

// 是否是编辑页面
const isEditPage = computed(() => {
    return props.type === 'add' || props.type === 'edit' || props.type === 'revision' ;
});

const handleOpen = (_type: string, id: string) => {
    type.value = _type;
    initFormData();
    if (type.value != "add") {
        loading.value = true;
        request.get(`/material/contract/${id}`).then((res) => {
            formData.value = {
                ...formData.value,
                ...res.data,
            };
            loading.value = false;
            emits("formSubmited", formData.value);
        });
    }
}

//明细
const handleDeleteDetailLimit = (index: number) => {
    formData.value.detailList.splice(index, 1);
}

const getData = (zt: number): Promise<any> => {
    let promise = new Promise((resolve, reject) => {
        formRef.value.validate((valid: boolean) => {
            if (valid) {
                resolve({
                    ...formData.value,
                });
            } else {
                reject();
            }
        })
    })
    return promise;
};


//物料清单
const vpBasedataMaterialDialog = ref();
const handleAddBasedataMaterial = () => {
    vpBasedataMaterialDialog.value.handleOpen({
        multi: true,
        callback: (obj: any) => {
            obj.forEach((item: any) => {
                formData.value.detailList.push({
                    wlid: item.id,
                    jh: item.jh,
                    zwms: item.zwms,
                    ywms: item.ywms,
                    xqmxid: "",
                    xqmxBh: "",
                    xqmxXc: "",
                    xlh: "",
                    sl: "",
                    jldw: item.jldw,
                    jhrq: "",
                    cqid: "",
                    cqBh: "",
                    cqName: "",
                })
            });
        }
    })
}

//产权
const vpBasedataPropertyRightsDialogRef = ref();
const handleAddPropertyRights = (row: any) => {
    vpBasedataPropertyRightsDialogRef.value.handleOpen({
        callback: (obj: any) => {
            row.cqid = obj.id;
            row.cqBh = obj.bh;
            row.cqName = obj.mc;
        }
    });
}

const handleAddPropertyRightsBeatch = () => {
    vpBasedataPropertyRightsDialogRef.value.handleOpen({
        callback: (obj: any) => {
            formData.value.detailList.forEach((row: any) => {
                row.cqid = obj.id;
                row.cqBh = obj.bh;
                row.cqName = obj.mc;
            });
        }
    });
}

//选择需求
const chooseMaterialDemandDialogRef = ref();
const handleAddMaterialDemandBeatch = () => {
    chooseMaterialDemandDialogRef.value.handleOpen({
        multi: true,
        callback: (obj: any) => {
            obj.forEach((item: any) => {
                formData.value.detailList.push({
                    wlid: item.wlid,
                    jh: item.jh,
                    zwms: item.zwms,
                    ywms: item.ywms,
                    xqmxid: item.demandDetailId,
                    xqmxBh: item.bh,
                    xqmxXc: item.xc,
                    xlh: "",
                    sl: "",
                    jldw: item.jldw,
                    jhrq: "",
                    cqid: "",
                    cqBh: "",
                    cqName: "",
                })
            });
        }
    });
}

const handleAddMaterialDemandSingle = (row: any) => {
    chooseMaterialDemandDialogRef.value.handleOpen({
        multi: false,
        callback: (item: any) => {
            if (Object.keys(item).length > 0) {
                row.xqmxBh = item.bh;
                row.xqmxXc = item.xc;
                row.xqmxid = item.demandDetailId;
                return;
            }
            row.xqmxBh = '';
            row.xqmxXc = '';
            row.xqmxid = '';
        }
    });
}

//选择供应商
const chooseQualitySupplierListDialogRef = ref();
const handleSupplierSelected = () => {
    chooseQualitySupplierListDialogRef.value.handleOpen({
        callback: (item: any) => {
            formData.value.xgflx = 10;
            formData.value.xgfid = item.id;
            formData.value.xgfms = item.gysbm
        }
    });
}

//统一设置交货期
const handleAddJhqBeatch = () => {
    const selectedTime = ref(null);
    ElMessageBox({
        title: '选择时间',
        message: () => h(ElDatePicker, {
            modelValue: selectedTime.value,
            'onUpdate:modelValue': (val) => {
                selectedTime.value = val;
            },
            type: 'date',
            placeholder: '请选择时间',
            style: 'width: 100%',
            popperAppendToBody: false,
            valueFormat: 'YYYY-MM-DD'
        }),
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        beforeClose: (action, instance, done) => {
            console.log('选中的时间：', selectedTime.value);

            if (action === 'confirm') {
                if (!selectedTime.value) {
                    ElMessage.warning('请选择时间');
                    return;
                }
                formData.value.detailList.forEach((row: any) => {
                    row.jhrq = selectedTime.value;
                });
                done();
            } else {
                done();
                ElMessage.info('已取消选择');
            }
        }
    });
};

defineExpose({
    getData
})

</script>
<style scoped>
:deep(.row-warning1) {
    color: var(--el-color-danger);
}

.box-item-content {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.header-item {
    display: flex;
    align-items: center;
    gap: 10px;
}
</style>